//
//  LogonView.m
//  playSerengetiMobile1
//
//  Created by Lita Gratrix on 10/24/09.
//  Copyright 2009 __MyComfile://localhost/Users/litagratrix/Documents/iPhone_SDK_workspace/playserengetimobile/Resources/MainView.xibpanyName__. All rights reserved.
//


#import "LogonView.h"
#import "playSerengetiMobile1AppDelegate.h"

@implementation LogonView

@synthesize appDelegate, emailField, passwordField, loginError, emailError, passwordError, email, password;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
	if (self = [super initWithNibName:@"LogonView"	bundle:nil]) {
	 self.appDelegate = (playSerengetiMobile1AppDelegate *)[[UIApplication sharedApplication] delegate];
 }
 return self;
 }


/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */



 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad {
 [super viewDidLoad];
 }


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }

- (void)logonSubmit:(id)sender {
	
	loginError.hidden = YES;
	emailError.hidden = YES;
	passwordError.hidden = YES;
	
	self.email = emailField.text;
	self.password = passwordField.text;
	
	if ([email length] == 0){
		emailError.hidden = NO;
	}
	if ([password length] == 0){
		passwordError.hidden = NO;
	}
	
	if([email length] != 0 && [password length] != 0){
		
		NSString *URLString = [NSString stringWithFormat:@"%@user/login", appDelegate.baseURL];
		NSURL *loginURL = [[NSURL alloc] initWithString:URLString];
		NSString *post = [NSString stringWithFormat:@"email=%@&password=%@&format=json", email, password];
//		NSLog(@"post is:%@\n", post);
		
		NSString *postEdit = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)post, NULL, CFSTR("!*'();:@+$,/?%#[]"), kCFStringEncodingUTF8);
//		NSLog(@"postEdit is:%@\n", postEdit);
		
		NSData *postData = [postEdit dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
//		NSLog(@"the post data looks like\n%@\n", postEdit);
		NSString *postLength = [NSString stringWithFormat:@"%d", [postEdit length]];
		
		
		NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
		[request setURL:loginURL];
		[request setValue:postLength forHTTPHeaderField:@"Content-Length"];  
		[request setValue:@"application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5" forHTTPHeaderField:@"Accept"];

		[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];  
		[request setHTTPBody:postData];  
		[request setHTTPMethod:@"POST"];
//		NSLog(@"HTTPBody is\n%@\n", [request HTTPBody]);
		NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
		
		if (conn){  
			responseData = [[NSMutableData data] retain];  
		}   
		else {  
			NSLog(@"Login Connection could not be made\n"); 
		} 
		[loginURL release];
	}
}

- (void)viewWillAppear:(BOOL)animated 
{
    // listen for keyboard hide/show notifications so we can properly adjust the table's height
	[super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewDidDisappear:(BOOL)animated 
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)aNotification 
{
	loginError.hidden = YES;
	// the keyboard is showing so resize the table's height
	CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue];
    NSTimeInterval animationDuration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect frame = self.view.frame;
    frame.size.height -= keyboardRect.size.height;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame = frame;
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)aNotification
{
    // the keyboard is hiding reset the table's height
	CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue];
    NSTimeInterval animationDuration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect frame = self.view.frame;
    frame.size.height += keyboardRect.size.height;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame = frame;
    [UIView commitAnimations];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (emailField == textField) {
        [emailField resignFirstResponder];
    }
	if (passwordField == textField){
		[passwordField resignFirstResponder];
	}
    return YES;
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

#pragma mark -
#pragma mark connection methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	[responseData setLength:0];

	NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
	NSDictionary *httpResponseHeaderFields = [httpResponse allHeaderFields];
//	NSLog(@"Connection did receive response: %@", httpResponseHeaderFields);
	appDelegate.JSessionCookieValue = [httpResponseHeaderFields objectForKey:@"Set-Cookie"];
	
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	NSLog(@"Login Error: %@\n", error);
	self.loginError.hidden = NO;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	[connection release];
	
//	NSLog(@"Succeeded! Received %d bytes of data\n",[responseData length]);  	
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//	NSLog(@"Returned Data: %@\n", responseString);
	[responseData release];
	responseData = nil;

	NSDictionary *parsedData = [responseString JSONValue];
	[responseString release];
	
	if (parsedData == nil) {
		NSLog(@"Login Error:");
		self.loginError.hidden = NO;
	} else {
		NSInteger tempId = [[parsedData objectForKey:@"id"] integerValue];
		appDelegate.loggedInAs = tempId;
//		NSLog(@"User is logging in as userId %d\n", appDelegate.loggedInAs);
//		NSLog(@"JSession Cookie value is %@\n", appDelegate.JSessionCookieValue);
		
		[appDelegate loadMainView];
	}
}


- (void)dealloc {
	[appDelegate release];
	[emailField release];
	[passwordField release];
	[loginError release];
	[emailError release];
	[passwordError release];
	[email release];
	[password release];
    [super dealloc];
}

@end